import { defineComponent, computed, reactive, ref, PropType, toRefs, nextTick, watch } from 'vue';
import { t } from '@src/locales'
import { ConnectorAppModuleListItem, ConnectorBizTypeEnum, ConnectorEditOptions, ConnectorField, ConnectorFromField, ConnectorOptionsAction, CreateConnectorModalFields } from '@src/modules/connector/model'

import FormConnectorDataRuleSettingDataSource, { FieldUpdateResult } from '@src/component/form/components/FormConnector/components/FormConnectorDataRuleSetting/components/FormConnectorDataRuleSettingDataSource'
import FormConnectorDataRuleSettingInterface from '@src/component/form/components/FormConnector/components/FormConnectorDataRuleSetting/components/FormConnectorDataRuleSettingInterface'
import FormConnectorDataRuleSettingFields from '@src/component/form/components/FormConnector/components/FormConnectorDataRuleSetting/components/FormConnectorDataRuleSettingFields'
import FormConnectorDataRuleSettingFilter, { ConnectorDialogDetailDataFilterData } from '@src/component/form/components/FormConnector/components/FormConnectorDataRuleSetting/components/FormConnectorDataRuleSettingFilter'


import '@src/component/form/components/FormConnector/components/FormConnectorDataRuleSetting/style/style.scss'
import { connectServerValueToComponentValueForEditWithTaskToPaas } from '@src/modules/connector/util';
import { CardInputTypeEnum } from '@model/enum/CardEnum';
import { ComponentEmitAction } from '@src/component/form/components/FormConnector/components/FormConnectorDataRuleSetting/model/enum/action';
import { cloneDeep, isArray, merge, mergeWith } from 'lodash';
import { uuid } from '@src/util/lang/string';
import Field from '@model/entity/Field';
import { message } from '@src/util/message';
import { generateConvertParams } from './utils/convert';


interface SettingDataInterface {
  dataSource: string [],
  interface: ConnectorOptionsAction | Record<string, any>,
  selectShowFieldNameList: string [],
  selectFormValue?: Record<string, any> | null,
  formConnectorDataRuleSettingFilterConfig?: ConnectorDialogDetailDataFilterData
}

enum DataSourceSettingMappingEnum {
  DataSource = 'dataSource',
  Interface = 'interface',
  SelectShowFieldNameList = 'selectShowFieldNameList',
  SelectFormValue = 'selectFormValue',
  FormConnectorDataRuleSettingFilterConfig = 'formConnectorDataRuleSettingFilterConfig'
}

export type FromAppData = Pick<ConnectorEditOptions, 'fromBizType' | 'fromBizTypeId'| 'conditionalLimit'>


export default defineComponent({
  props: {
    field: {
      type: Object as PropType<Field>,
      default: ()=> ({}) 
    },
    fromFields: {
      type: Array as PropType<ConnectorFromField[]>,
      default: ()=> ([])
    },
    templateName: {
      type: String as PropType<string>,
      default: ''
    },
    fromAppData: {
      type: Object as PropType<FromAppData>,
      default: ()=> ({})
    },
    isCreated: {
      type: Boolean as PropType<boolean>,
      default: ()=> false
    }
  },
  emits: [ComponentEmitAction.Input, 'updateForKey'],
  setup(props, { emit, expose }) {
    // eslint-disable-next-line vue/no-setup-props-destructure
    const { templateName, fromAppData, field, isCreated } = toRefs(props)
    const settingData = reactive<SettingDataInterface>({
      dataSource: [],
      interface: {},
      selectShowFieldNameList: [],
      selectFormValue: null
    })

    const formConnectorDataRuleSettingFilterKey = ref(uuid())
    const formConnectorDataRuleSettingDataSourceKey = ref(uuid())


    const formConnectorDataRuleSettingInterface = ref<typeof FormConnectorDataRuleSettingInterface>()
    const formConnectorDataRuleSettingFilter = ref<typeof FormConnectorDataRuleSettingFilter>()
    

    // 字段选择字段从接口选择中的toResponseFieldList去取
    const selectFields = computed(()=> settingData.interface?.toResponseFieldList || [])

    const isMulti = computed(() => Boolean(field.value?.setting?.isMulti))

    const handleUpdateData = (params: FieldUpdateResult, type: keyof SettingDataInterface)=> {
  

      if(type === DataSourceSettingMappingEnum.DataSource) {
        // 设置对应的dataSource的值
        settingData[type] = params.newValue

        // 置空除了相关选择数据来源的的数据
        handleRestValue()

        // 拿到对应的获取的选中表单的值
        const { selectItem } = params
        const { bizType, bizTypeId } = selectItem
        // 赋值对应寻找的表单（后续需要拿对应的bizType，bizTypeId ）
        settingData.selectFormValue = selectItem

        formConnectorDataRuleSettingInterface.value?.refreshFetchData({ bizTypeId, bizType})
      } 
      // 设置接口下拉菜单的值
      else if(type === DataSourceSettingMappingEnum.Interface) {
        settingData[type] = cloneDeep(params.selectItem ? params.selectItem : {})
        // 置空可选范围数据
        if(Object.keys(settingData[type]).length === 0) {
          handleRestValue()
        }

 
        const actionList = [params.selectItem] as unknown as ConnectorOptionsAction[]
        // 根据方法转对应的数据 --（connectServerValueToComponentValueForEditWithTaskToPaas）
        const detailValue = connectServerValueToComponentValueForEditWithTaskToPaas(
          generateConvertParams(
            actionList, 
            settingData.selectFormValue,
            fromAppData.value,
            props.fromFields
          )
        ) as unknown as ConnectorDialogDetailDataFilterData

        // 赋值fromApp的参数数据
        detailValue.fromApp = {
          name: templateName.value
        }


        // 相关可以选范围的数据设置操作逻辑
        const defaultDetailValue = settingData[DataSourceSettingMappingEnum.FormConnectorDataRuleSettingFilterConfig]

        // 为了清除后重新设置值问题
        if(defaultDetailValue?.actionList) {
          defaultDetailValue.actionList = actionList
          defaultDetailValue.toFieldList = actionList?.[0]?.toRequestFieldList || []
        }

        settingData[DataSourceSettingMappingEnum.FormConnectorDataRuleSettingFilterConfig] = defaultDetailValue ? defaultDetailValue : detailValue


        // 相关选中showFieldNameList的值设置逻辑
        const defaultShowFieldNameList = settingData[DataSourceSettingMappingEnum.SelectShowFieldNameList]
        settingData[DataSourceSettingMappingEnum.SelectShowFieldNameList] = defaultShowFieldNameList.length > 0 
          ? defaultShowFieldNameList 
          : (actionList?.[0]?.toResponseFieldList || []).slice(0, 5).map(field=> field.enName) // 这里是从选中的接口中toResponseFieldList里去取值

   
      } else {
        // 其他公共的设置值方法
        settingData[type] = params.newValue

        if(type === DataSourceSettingMappingEnum.FormConnectorDataRuleSettingFilterConfig) {
          // 强制更新组件
          nextTick(()=> formConnectorDataRuleSettingFilterKey.value = uuid())
        }
      }

      emit(ComponentEmitAction.Input, settingData)
      
    }

    const handleRestValue = () => {
      // 置空对应interface的值
      settingData[DataSourceSettingMappingEnum.Interface] = {}

      // 置空选中的selectShowFieldNameList
      settingData[DataSourceSettingMappingEnum.SelectShowFieldNameList] = []

      // 置空可选范围数据
      settingData[DataSourceSettingMappingEnum.FormConnectorDataRuleSettingFilterConfig] = undefined
    }

    const setDefaultData = (data: SettingDataInterface) => {

      if(!data || Object.keys(data).length === 0) return
 
      Object.keys(data).forEach((key) => {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        settingData[key] = data[key]
        if(key === DataSourceSettingMappingEnum.SelectFormValue) {
          const { bizTypeId, bizType } = data[DataSourceSettingMappingEnum.SelectFormValue] as unknown as any
          formConnectorDataRuleSettingInterface.value?.refreshFetchData({ bizTypeId, bizType})
        }
      })
    }


    // const generateConvertParams = (actionList: ConnectorOptionsAction [] = [])=> {
    //   const { 
    //     icon: toBizTypeLogo = '',  
    //     bizType: toBizType = '', 
    //     bizTypeId: toBizTypeId = '', 
    //     label: toBizTypeName = '' 
    //   } = settingData.selectFormValue ? settingData.selectFormValue : {}
    //   return {
    //     additionalId: -1, // 模拟值
    //     fromBizType: fromAppData.value.fromBizType, // 模拟值
    //     fromBizTypeId: fromAppData.value.fromBizTypeId,
    //     fromFieldList: fromFields.value,
    //     toFieldList: actionList[0].toRequestFieldList,
    //     insertFieldOptionsList: [],
    //     selectFieldOptionsList: [],
    //     addTime: CardInputTypeEnum.Multi, // 模拟值
    //     showFieldNameList: [],
    //     toBizType, 
    //     toBizTypeLogo, 
    //     toBizTypeId, 
    //     toBizTypeName, 
    //     actionList 
    //   }
    // }

    const updateSettingIsMulti = (v: any) => {
      // this.update(newValue, 'isMulti', isSetting)
      emit('updateForKey', Boolean(v), 'isMulti', true)
    }

    expose({
      setDefaultData
    })

    watch(()=> settingData[DataSourceSettingMappingEnum.DataSource], ()=> {
      formConnectorDataRuleSettingDataSourceKey.value = uuid()
    })


    // :value="isMulti"
    // @change="updateSettingIsMulti"
    // :disabled="Boolean(field.id)"

    return () =>(
      <div class="form-setting-group form-setting-item">
        <div class="form-setting-item-select">
          <h4 class="form-item-title">{t('common.connector.fieldSetting.title')}</h4>
        </div>
        <div class="form-item-box form-item-box_sub">
          <div class="form-setting-item-select">
            <h4 class="form-item-title">{t('common.connector.fieldSetting.dataSources')}</h4>
            <el-checkbox
              value={isMulti}
              disabled={Boolean(field.value.id)}
              onChange={updateSettingIsMulti}
            >
              { t('common.base.multiple') }
            </el-checkbox>
          </div>
          <div class="form-item-box">
            <FormConnectorDataRuleSettingDataSource 
              key={formConnectorDataRuleSettingDataSourceKey.value}
              value={settingData[DataSourceSettingMappingEnum.DataSource]} 
              isCreated={isCreated.value}
              onInput={(params: FieldUpdateResult)=> handleUpdateData(params, DataSourceSettingMappingEnum.DataSource)}/>
          </div>
          <div class="form-setting-item-select">
            <h4 class="form-item-title">{t('common.connector.fieldSetting.interfaceSelect')}</h4>
          </div>
          <div class="form-item-box">
            <FormConnectorDataRuleSettingInterface
              ref={formConnectorDataRuleSettingInterface}
              selectFormValue={settingData[DataSourceSettingMappingEnum.SelectFormValue]}
              onInput={(params: FieldUpdateResult)=> handleUpdateData(params, DataSourceSettingMappingEnum.Interface)}
              value={settingData.interface} />
          </div>
          <div class="form-setting-item-select">
            <h4 class="form-item-title">{ t('common.connector.fieldSetting.fieldSelect') }</h4>
          </div>
          <div class="form-item-box">
            <FormConnectorDataRuleSettingFields 
              fields={selectFields.value} 
              showFieldNameList={settingData.selectShowFieldNameList}
              onInput={(params: FieldUpdateResult)=> handleUpdateData(params, DataSourceSettingMappingEnum.SelectShowFieldNameList)}
            />
          </div>
          <div class="form-setting-item-select column-item-select">
            <h4 class="form-item-title">{ t('common.connector.scoped') }</h4>
            <span class="form-common-setting-title-remind">{ t('common.connector.fieldSetting.selectScope') }</span>
          </div>
          <div class="form-item-box form-item-box__filter">
            <FormConnectorDataRuleSettingFilter
              key={formConnectorDataRuleSettingFilterKey.value}
              ref={formConnectorDataRuleSettingFilter} 
              configData={settingData[DataSourceSettingMappingEnum.FormConnectorDataRuleSettingFilterConfig]}
              onInput={(params: FieldUpdateResult)=> handleUpdateData(params, DataSourceSettingMappingEnum.FormConnectorDataRuleSettingFilterConfig)}
            />
          </div>
        </div>
      </div>
    );
  },
});
